package com.deltapunkt.proxy;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class Logger implements Runnable {
	private BlockingDeque<String> logQueue;
	private volatile boolean stopped;
	private static ExecutorService exec;

	private Logger() {
		exec = Executors.newSingleThreadExecutor();
		logQueue = new LinkedBlockingDeque<String>();
		exec.execute(this);
	}

	public final static Logger it = new Logger();

	public synchronized void log(String msg) {
		logQueue.addLast(msg);
	}

	public void logHex(String key, byte v[]) {
		StringBuilder sb = new StringBuilder(key + ":" + v.length + ":");
		for (byte b : v) {
			sb.append(String.format("%02X ", b));
		}
		log(sb.toString());
	}

	public void run() {
		while(!stopped){
			try {
				String msg = logQueue.take();
				System.out.println(msg);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void stop() {
		stopped = true;
		exec.shutdownNow();
	}
}
